/**
 * Created by pankaj on 25/10/14.
 */
define(['jquery', 'mustache', 'summernote', 'module/template/homeTemplate', 'module/home/updateUploadFile',
        'module/home/customEvent', 'module/menu/dropdown', 'module/common/richbox'],
    function ($, Mustache, summernote, template, updateUploadFile, customEvent, Dropdown, richbox) {

    var showUpdateBox = function(fakeInput, options ){

        var showForm = function(event){


            var error = $('<div class="error"> <p class="alert-danger" > Please write what you want to update first in text area, then try ' +
                'to submit </p> </div>');
            var fakeInputParent = fakeInput.parent();
            var footer = fakeInputParent.siblings('div.panel-footer');
            footer.fadeIn();
            fakeInput.remove();
           // fakeInputParent.empty();
            var div = $(template['home-update-rich-text']);
            if(options.addTitle){
                fakeInputParent.append($(template['discussion-inputTitle']));
                fakeInputParent.find('input[type="text"]').focus();
            }



            fakeInputParent.append(div);

            if(options.addAgenda){
                fakeInputParent.append(options.addAgenda.dom);
            }

            div.summernote({
                focus :options.addTitle?false: true,
                hideToolBar : true,
                toolbar: richbox.sm_option
            });

            var fakeFileInput = footer.find('input[type=file]');
            var fileUpload = new updateUploadFile(fakeInputParent, fakeFileInput, footer.find('a.js_fileupload'));
            var dropDown = new Dropdown(footer, $.getJSON('/user/getGroup'));

            var restore = function(){
                footer.hide();
                dropDown.reset();
                fakeFileInput.files = [];
                div.destroy();
                fakeInputParent.empty();
                fakeInputParent.append(fakeInput);
                fakeInput.click(showForm);
            };

            footer.find('a.js_showfont').once('click', function(){
                div.showToolBar();
            });

            var submitForm = function(){
                var txt = div.code();
                var testCode = txt.replace(/&nbsp;/g,'');
                testCode = testCode.replace(/<p>/g,'');
                testCode = testCode.replace(/<\/p>/g,'');
                testCode = testCode.replace(/<br>/g,'');


                if(fakeInputParent.find('input[type="text"].js_title').length > 0){
                    var titleVal = fakeInputParent.find('input[type="text"].js_title').val();
                   if(titleVal.trim().length == 0){
                       fakeInputParent.prepend(error);
                       return;
                   }
                }

                if(testCode.trim().length == 0){
                    fakeInputParent.prepend(error);
                    return;
                }

                if(dropDown.getValue() < 0){
                    return;
                }

                if(options.addAgenda && !options.addAgenda.isValid()){
                    fakeInputParent.prepend(error);
                    return;
                }


                var ajaxObj = {};
                if(fileUpload.files.length != 0){

                    var formData = new FormData();
                    $.each(fileUpload.files, function(key, value){
                        formData.append('attached[]', value, value.name);
                    });
                    formData.append('update', txt);
                    formData.append('target', options.target ? options.target : dropDown.getValue());
                    formData.append('targetType',options.targetType ? options.targetType : 'group');
                    formData.append('updateType', options.updateType);
                    formData.append('title',  titleVal);
                    if(options.addAgenda){
                        formData.append('poll_data',  options.addAgenda.getValue());
                    }
                    ajaxObj = $.extend(ajaxObj,{
                        url : '/user/update',
                        type : "POST",
                        data : formData,
                        processData: false, // Don't process the files
                        contentType: false // Set content type to false as jQuery will tell the server its a query string request
                    });
                } else {
                    ajaxObj = $.extend(ajaxObj, {
                        url : '/user/update',
                        type : "POST",
                        data : {
                            update : txt,
                            target : options.target ? options.target : dropDown.getValue(),
                            targetType : options.targetType ? options.targetType : 'group',
                            updateType : options.updateType,
                            title :  titleVal
                        }
                    });

                    if(options.addAgenda){
                        ajaxObj.data = $.extend(ajaxObj.data, {
                            pollJson : options.addAgenda.getValue()
                        });
                    }
                }

                fakeInputParent.empty();
                var loader = template.small_loader;
                fakeInputParent.append(loader);
                $.ajax(ajaxObj).done(function() {
                    restore();
                    var eventType = customEvent.UPDATE_PAGE;
                    if(options.updateType == '5'){
                        eventType = customEvent.UPDATE_DISCUSSION;
                    }
                    $.event.trigger({
                        type : eventType,
                        append : false
                    });
                    // update module factory
                }).fail(function() {
                    alert('oops ..');
                });
            };

            footer.find('button.submit').once('click', submitForm);
            footer.find('button.cancel').once('click', function(){
                restore();
            });

        };
        fakeInput.once('click',showForm);
        // initialize drop-down menu.
    };





    return showUpdateBox;
});
